package com.itheima.algorithm.hashtable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class E03Leetcode49 {
    public List<List<String>> groupAnagrams1(String[] strs){
        HashMap<String,List<String>> map=new HashMap<>();

        for(String str:strs){
            //将遍历到的数组排序
            char[] chars=str.toCharArray();
            Arrays.sort(chars);

            String key=new String(chars);
            List<String> list=map.get(key);

            //如果这种类型的key不存在，先建立空数组
            if(list==null){
                list=new ArrayList<>();
                map.put(key,list);
            }
            list.add(str);
        }
        return new ArrayList<>(map.values());
    }

    static class ArrayKey{
        int[] key=new int[26];

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof ArrayKey arrayKey)) return false;
            return Arrays.equals(key, arrayKey.key);
        }

        @Override
        public int hashCode() {
            return Arrays.hashCode(key);
        }

        public ArrayKey(String str){
            for(int i=0;i<str.length();i++){
                char ch=str.charAt(i);
                key[ch-'a']++;
            }
        }
    }

    public List<List<String>> groupAnagrams(String[] strs){
        HashMap<ArrayKey,List<String>> map=new HashMap<>();
        for(String str:strs){
            ArrayKey key=new ArrayKey(str);
            List<String> list=map.computeIfAbsent(key,k->new ArrayList<>());
            list.add(str);
        }
        return new ArrayList<>(map.values());
    }
}
